
import { Toast } from "antd-mobile";
import { isEmptyString } from "@/utils/utils";
import { UrlDoLogin, UrlGetOtp } from "@/utils/apiUrl";
import http, { baseParams } from "@/utils/request";


/**
 * 获取验证码
 * @param {String } mobile 手机号
 * @param {function } reqCallback 响应返回
 * @returns thunk
 */
export const getOtp = (path, mobile, reqCallback) => {
    return async dispatch => {
        console.log("getOtp: " + path + ", " + mobile);

        //组装参数
        const params = baseParams()
        params.mobile = mobile

        //发起请求
        const res = await http.post(path + UrlGetOtp, params);

        console.log(res);
        const resCode = parseInt(res.code)
        const resObj = res.data
        const resMsg = res.msg
        console.log("获取验证码-结束：=======")

        //保存
        const success = (resCode === 0)

        //如果有错误，提示
        if (!success) {
            if (!isEmptyString(resMsg)) {
                Toast.show(resMsg, 1)
            }
        }

        //回调
        reqCallback && reqCallback(success, resObj)
    }
}

/**
 * 登录
 * @param {String } mobile 手机号
 * @param {String } code 验证码
 * @param {function } reqCallback 响应返回
 * @returns thunk
 */
export const doLogin = (path, mobile, code, reqCallback) => {
    return async dispatch => {
        console.log("doLogin: " + path + "," + mobile + " , " + code);

        //组装参数
        const sourceRegChannelCode = process.env.REACT_APP_CHANNEL_CODE + "";
        const params = baseParams()
        params.mobile = mobile + ""
        params.code = code + ""
        params.docReferrer = document.referrer || ""
        params.sourceRegChannelCode = sourceRegChannelCode

        //发起请求
        const res = await http.post(path + UrlDoLogin, params);

        console.log(res);
        const resCode = parseInt(res.code)
        const resObj = res.obj
        const resMsg = res.msg
        console.log("登录-结束：=======")

        //保存
        const success = (resCode === 0)

        //如果有错误，提示
        if (!success) {
            if (!isEmptyString(resMsg)) {
                Toast.show(resMsg, 1)
            }
        }

        //回调
        reqCallback && reqCallback(success, resObj)
    }
}